<?php

namespace App\Http\Controllers\Laifei\Settlement;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SettlementExploreController extends Controller
{

    public function index()
    {

        $all = $this->all;
        $pageSize = $all['pageSize'] ?? 20;
        $pageNo = $all['pageNo'] ?? 1;
        try {
            $where = function ($query) use ($all) {
                if (isset($all['work_no'])) {
                    $query->where('es.work_no', '=', $all['work_no']);
                }
                if (isset($all['openid'])) {
                    $query->where('es.openid', '=', $all['openid']);
                }
                if (isset($all['date']) && $all['date'] !== []) {
                    $date = [$all['date'][0] . ' 00:00:00', $all['date'][1] . ' 23:59:59'];
                    $query->whereBetween('es.created_at', $date);
                }
            };
            $total = DB::table('explore_settlement as es')->where($where)->count();
            $info = DB::table('explore_settlement as es')
                ->leftJoin('lottery_users as lu', 'es.we_id', '=', 'lu.we_id')
                ->where($where)
                ->select('es.settlement_id', 'es.work_id', 'es.work_no', 'es.we_id', 'lu.nickname', 'es.openid','es.received','es.rcv_time','es.reason',
                    'es.total_amount', 'es.payment_amount', 'es.service_fee', 'es.created_at')
                ->orderByDesc('es.created_at')
                ->skip(($pageNo - 1) * $pageSize)
                ->take($pageSize)
                ->get()
                ->map(function ($item) {
                    $item->total_price = $item->total_amount / 100.00;
                    $item->payment_price = $item->payment_amount / 100.00;
                    $item->service_price = $item->service_fee / 100.00;
                    return $item;
                })
                ->toArray();

            return $this->setReturnJson(0, 'success', ['total' => $total, 'info' => $info]);

        } catch (\Exception $e) {
            Log::error(SettlementExploreController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '查询失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }

    }

}
